from django.shortcuts import redirect
from django.urls import reverse
from django.conf import settings

class AuthMiddleware:
    """路由守卫中间件"""
    
    def __init__(self, get_response):
        self.get_response = get_response
        # 不需要登录的路径
        self.public_paths = [
            '/',
            '/login/',
            '/regist/',
            '/captcha/',
            '/admin/',
        ]
    
    def __call__(self, request):
        # 检查是否为公开路径
        if not any(request.path.startswith(path) for path in self.public_paths):
            # 如果用户未登录，重定向到登录页面
            if not request.user.is_authenticated:
                return redirect('/')
        
        response = self.get_response(request)
        return response